import { defineStore } from "pinia";
// import piniaPersistConfig from "@/stores/helper/persist";
import apiService from "@/api/services/apiService";
import { Org, ParamExts, Product, Roles, Users } from "@/api/types/base";
import { DataState } from "../interface";
import { Model } from "@/views/model/modeTypes";

export const useDataStore = defineStore({
  id: "base-data",
  state: (): DataState => ({
    enumData: new Map<string, ParamExts[]>(),
    commonData: new Map<string, any[]>(),
    userList: [],
    productList: [],
    orgList: [],
    orgTree: [],
    roleList: [],
    abstractElements: [],
    dataElements: [],
    userId: ""
  }),
  getters: {
    getDataByKey: state => key => {
      let finalKey = state.userId + "-" + key;
      if (state.commonData.has(finalKey)) {
        console.log("获取缓存数据，缓存KEY:" + key);
        return state.commonData.get(finalKey) || [];
      } else {
        return [];
      }
    },
    getEnumByCsName:
      state =>
      (csName: string): ParamExts[] => {
        return (csName && state.enumData.get(csName)) || [];
      },
    getCommonDataByName: state => key => {
      let finalKey = state.userId + "-" + key;
      if (state.commonData.has(finalKey)) {
        console.log("获取缓存数据，缓存KEY:" + key);
        return state.commonData.get(finalKey) || [];
      } else {
        return [];
      }
    },
    getOrgListByType: state => type => {
      return state.orgList.filter(org => org.type === type);
    }
  },
  actions: {
    async findList(key, requestApi): Promise<any[]> {
      let finalKey = this.userId + "-" + key;
      return new Promise(async resolve => {
        if (key && !this.commonData.has(finalKey)) {
          let { data } = await requestApi({});
          this.commonData.set(finalKey, data);
        }
        let result = this.commonData.get(finalKey);
        if (result) {
          resolve(result);
        }
        console.log(this.commonData);
      });
    },
    async findOrgList(): Promise<Org[]> {
      return new Promise(async resolve => {
        if (this.orgList && this.orgList.length == 0) {
          const options = {
            fields: ["_id", "name", "type", "sort"],
            sort: {
              sort: 1
            }
          };
          let { data } = await apiService.find<Org[]>("orgs", {}, options);
          this.orgList = data;
        } else {
          resolve(this.orgList);
        }
      });
    },
    async findRoleList(): Promise<Roles[]> {
      return new Promise(async resolve => {
        if (this.roleList && this.roleList.length == 0) {
          const options = {
            fields: ["_id", "name"]
          };
          let { data } = await apiService.find<Roles[]>("roles", {}, options);
          this.roleList = data;
        } else {
          resolve(this.roleList);
        }
      });
    },
    async findOrgTree(): Promise<Org[]> {
      return new Promise(async resolve => {
        if (this.orgTree && this.orgTree.length == 0) {
          let { data } = await apiService.findTree<Org[]>("orgs", {}, { sort: { sort: 1 }, fields: ["_id", "pid", "name"] });
          this.orgTree = data;
        } else {
          resolve(this.orgTree);
        }
      });
    },
    async findProductList(): Promise<Product[]> {
      return new Promise(async resolve => {
        if (this.productList && this.productList.length == 0) {
          const options = {
            fields: ["_id", "name"],
            sort: {
              name: 1
            }
          };
          let { data } = await apiService.find<Product[]>("product", {}, options);
          this.productList = data;
        } else {
          resolve(this.productList);
        }
      });
    },
    async findUserList(): Promise<Users[]> {
      return new Promise(async resolve => {
        if (this.userList && this.userList.length == 0) {
          const options = {
            fields: ["_id", "userName", "orgId", "userPicId"],
            sort: {
              userName: 1
            }
          };
          let { data } = await apiService.find<Users[]>("users", {}, options);
          this.userList = data;
          resolve(this.userList);
        } else {
          resolve(this.userList);
        }
      });
    },
    async findAbstractElements(): Promise<Model.AbstractElement[]> {
      return new Promise(async resolve => {
        if (this.abstractElements && this.abstractElements.length == 0) {
          const options = {
            fields: ["cnName", "enName"]
          };
          let { data } = await apiService.find<Model.AbstractElement[]>("abstractElement", {}, options);
          this.abstractElements = data;
          resolve(this.abstractElements);
        } else {
          resolve(this.abstractElements);
        }
      });
    },
    async findDataElements(): Promise<Model.DataElement[]> {
      return new Promise(async resolve => {
        if (this.abstractElements && this.abstractElements.length == 0) {
          const options = {
            fields: ["cnName", "enName", "description"]
          };
          let { data } = await apiService.find<Model.DataElement[]>("dataElement", {}, options);
          this.dataElements = data;
          resolve(this.dataElements);
        } else {
          resolve(this.dataElements);
        }
      });
    },
    async findEnumByCsName(csName: string): Promise<ParamExts[]> {
      return new Promise(async (resolve, reject) => {
        if (this.enumData && !this.enumData.has(csName)) {
          let { data } = await apiService.findClassify<ParamExts[]>(csName);
          this.enumData.set(csName, data);
        }
        let result = this.enumData.get(csName);
        if (result?.length && result.length > 0) {
          resolve(result);
        } else {
          reject(`${csName}枚举未配置`);
        }
      });
    }
  }
});
